<template>
  <ShopLayout>
    <div class="min-h-screen bg-gray-50 py-8">
      <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- 页面标题 -->
        <div class="mb-8">
          <h1 class="text-2xl font-bold text-gray-900">订单支付</h1>
          <p class="text-gray-600 mt-2">订单号：{{ order.order_number }}</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <!-- 订单信息 -->
          <div class="space-y-6">
            <!-- 订单商品 -->
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
              <h2 class="text-lg font-semibold text-gray-900 mb-4">订单商品</h2>
              <div class="space-y-4">
                <div
                  v-for="item in order.items"
                  :key="item.id"
                  class="flex items-center space-x-4 p-4 bg-gray-50 rounded-xl"
                >
                  <img
                    :src="item.product?.images?.[0]?.image_path || '/images/product-placeholder.svg'"
                    :alt="item.product_name"
                    class="w-16 h-16 object-cover rounded-lg"
                  />
                  <div class="flex-1 min-w-0">
                    <h3 class="text-sm font-medium text-gray-900 truncate">
                      {{ item.product_name }}
                    </h3>
                    <p v-if="item.variant_name" class="text-xs text-gray-500 mt-1">
                      {{ item.variant_name }}
                    </p>
                    <p class="text-sm text-gray-600 mt-1">
                      数量：{{ item.quantity }}
                    </p>
                  </div>
                  <div class="text-right">
                    <p class="text-sm font-medium text-gray-900">
                      ¥{{ (item.price * item.quantity).toLocaleString() }}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <!-- 收货地址 -->
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
              <h2 class="text-lg font-semibold text-gray-900 mb-4">收货地址</h2>
              <div class="p-4 bg-gray-50 rounded-xl">
                <p class="text-sm text-gray-900">
                  {{ order.receiver_name }} {{ order.receiver_phone }}
                </p>
                <p class="text-sm text-gray-600 mt-1">
                  {{ order.receiver_address }}
                </p>
              </div>
            </div>
          </div>

          <!-- 支付信息 -->
          <div class="space-y-6">
            <!-- 支付方式选择 -->
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
              <h2 class="text-lg font-semibold text-gray-900 mb-4">选择支付方式</h2>
              <div class="space-y-3">
                <label
                  v-for="method in paymentMethods"
                  :key="method.value"
                  class="flex items-center p-4 border border-gray-200 rounded-xl cursor-pointer hover:border-gray-300 transition-colors"
                  :class="{ 'border-gray-900 bg-gray-50': selectedPaymentMethod === method.value }"
                >
                  <input
                    v-model="selectedPaymentMethod"
                    :value="method.value"
                    type="radio"
                    name="payment_method"
                    class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300"
                  />
                  <div class="ml-3 flex items-center">
                    <div class="w-8 h-8 flex items-center justify-center">
                      <i :class="method.icon" class="text-xl"></i>
                    </div>
                    <div class="ml-3">
                      <p class="text-sm font-medium text-gray-900">{{ method.name }}</p>
                      <p class="text-xs text-gray-500">{{ method.description }}</p>
                    </div>
                  </div>
                </label>
              </div>
            </div>

            <!-- 订单金额 -->
            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
              <h2 class="text-lg font-semibold text-gray-900 mb-4">订单金额</h2>
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">商品金额</span>
                  <span class="text-gray-900">¥{{ order.subtotal_amount.toLocaleString() }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">运费</span>
                  <span class="text-gray-900">¥{{ order.shipping_fee.toLocaleString() }}</span>
                </div>
                <div v-if="order.discount_amount > 0" class="flex justify-between text-sm">
                  <span class="text-gray-600">优惠</span>
                  <span class="text-red-600">-¥{{ order.discount_amount.toLocaleString() }}</span>
                </div>
                <div v-if="order.user_coupon" class="flex justify-between text-sm">
                  <span class="text-gray-600">优惠券</span>
                  <div class="text-right">
                    <span class="text-red-600">-¥{{ (order.user_coupon.discount_amount || order.discount_amount || 0).toLocaleString() }}</span>
                    <p class="text-xs text-gray-500">{{ order.user_coupon.coupon.name }}</p>
                  </div>
                </div>
                <div class="border-t border-gray-200 pt-3">
                  <div class="flex justify-between">
                    <span class="text-base font-semibold text-gray-900">应付金额</span>
                    <span class="text-xl font-bold text-gray-900">¥{{ order.total_amount.toLocaleString() }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 支付按钮 -->
            <button
              @click="handlePayment"
              :disabled="!selectedPaymentMethod || isProcessing"
              class="w-full bg-gray-900 text-white py-4 px-6 rounded-2xl font-medium hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              <span v-if="isProcessing">处理中...</span>
              <span v-else>立即支付 ¥{{ order.total_amount.toLocaleString() }}</span>
            </button>

            <!-- 支付说明 -->
            <div class="text-xs text-gray-500 text-center">
              <p>点击"立即支付"即表示您同意遵守我们的服务条款</p>
              <p class="mt-1">支付完成后，订单将自动确认</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </ShopLayout>
</template>

<script setup>
import { ref } from 'vue'
import { router } from '@inertiajs/vue3'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  order: {
    type: Object,
    required: true
  },
  payment: {
    type: Object,
    required: true
  }
})

const { showSuccess, showError } = useNotification()

const selectedPaymentMethod = ref('')
const isProcessing = ref(false)

// 支付方式选项
const paymentMethods = [
  {
    value: 'alipay',
    name: '支付宝',
    description: '安全便捷的在线支付',
    icon: 'fas fa-credit-card text-blue-500'
  },
  {
    value: 'wechat',
    name: '微信支付',
    description: '微信用户首选支付方式',
    icon: 'fab fa-weixin text-green-500'
  },
  {
    value: 'mock',
    name: '模拟支付',
    description: '测试环境专用（无需真实支付）',
    icon: 'fas fa-test-tube text-orange-500'
  }
]

// 处理支付
const handlePayment = async () => {
  if (!selectedPaymentMethod.value) {
    showError('请选择支付方式', '')
    return
  }

  isProcessing.value = true

  try {
    const response = await fetch(route('payment.pay', props.order.order_number), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
      },
      body: JSON.stringify({
        payment_method: selectedPaymentMethod.value
      })
    })

    const result = await response.json()

    if (result.success) {
      // 支付成功，使用 Inertia.js 跳转到订单详情页
      showSuccess('支付成功！', '订单已确认，正在为您处理。')
      router.visit(route('order.show', result.order_number || props.order.order_number))
    } else {
      showError('支付失败', result.message || '请稍后重试')
    }
  } catch (error) {
    console.error('Payment error:', error)
    showError('支付失败', '网络错误，请稍后重试')
  } finally {
    isProcessing.value = false
  }
}
</script>